package com.easylinkin.linkappapi.iaqi.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easylinkin.linkappapi.common.service.CommonService;
import com.easylinkin.linkappapi.common.utils.DateUtil;
import com.easylinkin.linkappapi.iaqi.dao.IaqiStatisticMapper;
import com.easylinkin.linkappapi.iaqi.entity.IaqiStatistic;
import com.easylinkin.linkappapi.iaqi.entity.vo.CountDaysVo;
import com.easylinkin.linkappapi.iaqi.service.IaqiStatisticService;
import com.easylinkin.linkappapi.security.context.LinkappUserContextProducer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.*;

/**
 * IiaqiStatistic表服务实现类
 *
 * @author CodeGenerator
 * @date 2022/06/27
 */
@Slf4j
@Service("appIaqiStatisticService")
public class IaqiStatisticServiceImpl extends ServiceImpl
        <IaqiStatisticMapper, IaqiStatistic> implements IaqiStatisticService {
    @Resource
    private CommonService commonService;
    @Resource
    private LinkappUserContextProducer linkappUserContextProducer;

    @Override
    public boolean saveOne(IaqiStatistic appIaqiStatistic) {
//        commonService.setCreateAndModifyInfo(appIaqiStatistic);
//        appIaqiStatistic.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
        appIaqiStatistic.setCreateTime(new Date());
        validParamRequired(appIaqiStatistic);
        validRepeat(appIaqiStatistic);
        validParamFormat(appIaqiStatistic);
        return save(appIaqiStatistic);
    }

/*
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateOne(IaqiStatistic appIaqiStatistic) {
//        Assert.notNull(appIaqiStatistic.getId(), "id不能为空");
        commonService.setModifyInfo(appIaqiStatistic);
        appIaqiStatistic.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
        validRepeat(appIaqiStatistic);
        validParamFormat(appIaqiStatistic);
        return updateById(appIaqiStatistic);
    }

    @Override
    public IPage<IaqiStatistic> selectPage(Page page, IaqiStatistic appIaqiStatistic) {
        appIaqiStatistic.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
        return baseMapper.selectPage(page, appIaqiStatistic);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteByIds(List<Long> idList) {
        return removeByIds(idList);
    }

    @Override
    public void export(IaqiStatistic appIaqiStatistic, HttpServletRequest request, HttpServletResponse
            response) {

        IPage<IaqiStatistic> page = selectPage(new Page(0, -1), appIaqiStatistic);
        List<IaqiStatistic> records = page.getRecords();
        List
                <IaqiStatisticVo> appIaqiStatisticVos = new ArrayList<>();
        for (IaqiStatistic expert : records) {
            appIaqiStatisticVos.add(new IaqiStatisticVo(expert));
        }

        String keyValue = "名称:name,租户id:tenantId";
        String title = "IiaqiStatistic导出数据";
        String fileName = title + ".xls";
        try {
            OutputStream outputStream = OutputStreamUtil
                    .getOutputStream(request, response, fileName);
            ExcelTools.exportExcel(outputStream, keyValue, appIaqiStatisticVos, ExcelConstant.XLS, title);
            response.flushBuffer();
            outputStream.close();
        } catch (IOException e) {
            log.error("excel导出失败", e);
            throw new RuntimeException("excel导出失败！IOException异常" + e.getMessage());
        } catch (Exception e) {
            log.error("excel导出失败", e);
            throw new RuntimeException("excel导出失败！" + e.getMessage());
        }
    }

    @Override
    public IaqiStatistic getOneById(Serializable id) {
        return baseMapper.getOneById(id);
    }*/

    /**
     * 校验重复
     */
    private void validRepeat(IaqiStatistic appIaqiStatistic) {
//        QueryWrapper<IiaqiStatistic> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("name", appIaqiStatistic.getName());
//        queryWrapper.eq("tenant_id", linkappUserContextProducer.getNotNullCurrent().getTenantId());
//        List<IiaqiStatistic> list = baseMapper.selectList(queryWrapper);
//        if (list.size() == 0) {
//            return;
//        }
//        if (list.size() > 1) {
//            throw new BusinessException("名称有重复");
//        }
//        if (ObjectUtils.isEmpty(appIaqiStatistic.getId())) {
//            throw new BusinessException("名称已存在");
//        }
//        if (!appIaqiStatistic.getId().equals(list.get(0).getId())) {
//            throw new BusinessException("名称已存在");
//        }

    }


    /**
     * 校验参数必填
     */
    private void validParamRequired(IaqiStatistic appIaqiStatistic) {
        Assert.notNull(appIaqiStatistic, "参数为空");
//        Assert.isTrue(StringUtils.isNotBlank(appIaqiStatistic.getName()), "名称为空");
    }

    /**
     * 校验参数格式
     */
    private void validParamFormat(IaqiStatistic appIaqiStatistic) {
//        Assert.isTrue(appIaqiStatistic.getName() == null || appIaqiStatistic.getName().length() <= 50,
//                "名称超长");
    }

    @Override
    public List<CountDaysVo> countDaysGroupByLevel(CountDaysVo countDaysVo) {
        countDaysVo.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.MILLISECOND, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
//        最近30天从 ，不包括今日，由于今日还未结束，昨天是第一天算起，所以不需要 add 1
        String end = DateUtil.getYYYYMMDDHHMMSSDate(calendar.getTime());
        if (countDaysVo.getQueryType() == 1) {
            calendar.add(Calendar.DAY_OF_MONTH, -30);
        } else if (countDaysVo.getQueryType() == 2) {
            calendar.add(Calendar.MONTH, -3);
        } else if (countDaysVo.getQueryType() == 3) {
            calendar.add(Calendar.MONTH, -12);
        }
        String start = DateUtil.getYYYYMMDDHHMMSSDate(calendar.getTime());
        countDaysVo.setQueryTimeEnd(end);
        countDaysVo.setQueryTimeStart(start);

        List<CountDaysVo> list = baseMapper.countDaysGroupByLevel(countDaysVo);
        int sum = 0;
        Set<Integer> set = new HashSet();
        for (CountDaysVo daysVo : list) {
            sum += daysVo.getTotal();
            set.add(daysVo.getLevel());
        }
        //        最多有6个等级
        for (int i = 1; i <= 6; i++) {
            if (!set.contains(i)) {
                list.add(new CountDaysVo(i, 0));
            }
        }

        for (CountDaysVo daysVo : list) {
            daysVo.setSum(sum);
        }

        return list;
    }
}

